package com.toolset.Util;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//快递查询SDK
//https://www.woyaocha.net/product/express
public class ExpressUtil {

    public static String apiurl="http://cha.ebaitian.cn/api/json";  //接口地址
    public static String appid="10000424";                           //接口appid
    public static String appkey="c642fca618bd63c007d979aef606a7c2";  //接口appkey
    public static String module="getExpressInfo";                  //类型

    //sign加密
    public static String getSHA256Str(String str){
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));

            encdeStr = String.valueOf(Hex.encodeHex(hash));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }


    //通过单号查询快递
    public static String queryExpress(String order){
        String sign=getSHA256Str("appid="+appid+"&module="+module+"&order="+order+"&appkey="+appkey);
        String url=apiurl+"?type=get&appid="+appid+"&module="+module+"&order="+order+"&sign="+sign;

        return unicodeDecode(HttpUtil.Get(url));
    }


    //unicode 解析 中文
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

    public static void main(String[] args) {
        System.out.println(queryExpress("3708264389074"));
    }

}
